<template>
	<view class="cat2bug-body" :style="'height: ' + bodyHeight + ';'">
		<view class="header">
			<slot name="header"></slot>
		</view>
		<scroll-view
			class="cat2bug-body-content"
			scroll-y
			@scrolltolower="handleLowerRefresher"
			@scrolltoupper="handleToupperRefresher"
			@refresherrefresh="handleRefresher"
			:refresher-enabled="refresherEnabled"
			:refresher-triggered="refresherTriggered"
		>
			<slot name="content"></slot>
		</scroll-view>
		<view class="footer">
			<slot name="footer"></slot>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'PageBody',
		data() {
			return {
				// 显示内容元素的高度
				bodyHeight: 0,
			}
		},
		props: {
			// 列表是否在下拉刷新状态(设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发)
			refresherTriggered: {
				type: Boolean,
				default: false
			},
			// 是否可以下拉刷新
			refresherEnabled: {
				type: Boolean,
				default: false
			},
			safeBottom: {
				type: Boolean,
				default: false
			},
			// 偏移底部高度
			offsetBottom: {
				type: [Number, String],
				default: 0
			},
		},
		watch: {
			safeBottom: function(n, o) {
				this.calcBodyHeight(n);
			}
		},
		onReady() {
			this.calcBodyHeight(this.safeBottom);
		},
		computed: {
			/** 底部安全区域高度 */
			safeBottomHeight: function() {
				const systemInfo = uni.getSystemInfoSync();
				if (systemInfo.safeAreaInsets && systemInfo.safeAreaInsets.bottom > 0) {
				    return systemInfo.safeAreaInsets.bottom;
				}
				if (systemInfo.safeArea && systemInfo.safeArea.bottom) {
				    return systemInfo.screenHeight + systemInfo.safeArea.bottom;
				}
				if (systemInfo.windowBottom !== undefined) {
				    return systemInfo.windowBottom;
				}
				return 0;
			}
		},
		methods: {
			/** 计算body的高度 */
			calcBodyHeight(isSafeBottom) {
				const query = uni.createSelectorQuery().in(this);
				query.select('.cat2bug-body').boundingClientRect(rect => {
				  if (rect) {
					const safeBottom = isSafeBottom?this.safeBottomHeight:0;
					this.bodyHeight = `calc(100vh - ${rect.top}px - ${this.offsetBottom}px - ${safeBottom}px)`;
				  }
				}).exec();
			},
			/** 处理滚动到最底端刷新事件 */
			handleLowerRefresher() {
				this.$emit('scrolltolower');
			},
			handleToupperRefresher() {
				this.$emit('scrolltoupper');
			},
			/** 处理下拉刷新事件 */
			handleRefresher() {
				this.$emit('refresherrefresh');
			},
		}
	}
</script>

<style lang="scss" scoped>
	.cat2bug-body {
		width: 100vw;
		display: inline-flex;
		flex-direction: column;
		> * {
			flex-shrink: 0;
		}
		> .cat2bug-body-content {
			flex: 1;
			overflow-y: auto;
		}
		
	}
	.header, .footer {
		display: contents;
		width: 100%;
	}
</style>